package com.lb.uts.web;

import com.lb.uts.constants.BaseResponse;
import com.lb.uts.constants.UTSConstants;
import com.lb.uts.entity.JobExecuteRecord;
import com.lb.uts.entity.JobSearch;
import com.lb.uts.service.IJobRecordService;
import com.lb.uts.service.IScheduleJobService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.ZoneOffset;

/**
 * 定时记录操作
 *
 * @Author liangb
 * @Date 2019/4/26 15:18
 */
@Controller
@RequestMapping("record")
public class RecordController extends UtsBaseController {

    private static final Logger logger = LoggerFactory.getLogger(RecordController.class);

    @Autowired
    private IJobRecordService recordService;

    @Autowired
    private IScheduleJobService scheduleJobService;

    /**
     * 分页查询
     */
    @RequestMapping("list")
    public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize, String status, JobSearch jobSearch) {
        status = StringUtils.isEmpty(status) ? null : status;
        model.addAttribute("page", recordService.queryList(pageNo, pageSize, status, jobSearch));
        model.addAttribute("status", status);
        model.addAttribute("jobSearch", jobSearch);
        return "record/list";
    }

    /**
     * 手动终止一个任务
     * 前置条件：创建时间>=超时时间(TIME_OUT)
     */
    @RequestMapping("stop/{id}")
    @ResponseBody
    public BaseResponse delete(@PathVariable("id") String id) {
        logger.info("终止的id:" + id);
        JobExecuteRecord record = recordService.getById(id);
        if (record == null) {
            return wrapErrResp(BaseResponse.class, "记录不存在");
        }
        if (System.currentTimeMillis() - record.getStartTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() < UTSConstants.TIME_OUT) {
            return wrapErrResp(BaseResponse.class, "没有超过限制时间，请稍后重试");
        }
        //修改条数
        recordService.updateFailRecord(null, null, record.getId(), "人为终止");
        return wrapSuccessResp(BaseResponse.class);
    }
}
